//
//  YXYSkipViewController.m
//  Topit
//
//  Created by dllo on 15/12/7.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "YXYSkipViewController.h"
#import "YXYZoomImageModel.h"
#import "YXYZoomIdTableViewCell.h"
#import "YXYScrollImageTableViewCell.h"
#import "YXYZoomSelectionTableViewCell.h"
//#import "ParallaxHeaderView.h"
#import "DataBaseHandle.h"
#import "YXYSkipJumpViewController.h"
@interface YXYSkipViewController ()<UITableViewDataSource, UITableViewDelegate, scrollImageDataSource>
@property (nonatomic, assign) BOOL click;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, retain) NSMutableArray *dataSource;
@property (nonatomic, retain) NSMutableArray *urlArray;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, assign) CGFloat kHeight;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) UIImageView *downloadImage;
@end

@implementation YXYSkipViewController

- (void)dealloc {
//    NSLog(@"%s", __func__);
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [_imageView release];
    [_url release];
    [_dataSource release];
    [_tableView release];
    [_urlArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backDidButton:)];
    
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    self.urlArray = [NSMutableArray arrayWithCapacity:0];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[YXYZoomIdTableViewCell class] forCellReuseIdentifier:@"YXYZoomIdTableViewCellIdentifier"];
    [_tableView registerClass:[YXYScrollImageTableViewCell class] forCellReuseIdentifier:@"YXYScrollImageTableViewCellIdentifier"];
    [_tableView registerClass:[YXYZoomSelectionTableViewCell class] forCellReuseIdentifier:@"YXYZoomSelectionTableViewCellIdentifier"];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.mode = MBProgressHUDModeIndeterminate;
    [YXYNetWorkTool getWithUrl:_url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        for (NSDictionary *dic in result[@"item"]) {
            YXYZoomImageModel *zoomImageModel = [[YXYZoomImageModel alloc] initWithDictionary:dic];
            [_dataSource addObject:zoomImageModel];
            [zoomImageModel release];
        }
        [hud hide:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setUpImage];
            [_tableView reloadData];
        });
    } fail:^(NSError *error) {
        [hud hide:YES];
        [ProgressHUD showError:@"请检查网络"];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(shareDidPress:)];
    // Do any additional setup after loading the view.
}
- (void)setUpImage {
    YXYZoomImageModel *zoomModle = [_dataSource lastObject];
    NSString *str = zoomModle.icon[@"height"];
    self.kHeight = str.floatValue / 2;
    self.tableView.contentInset = UIEdgeInsetsMake(self.kHeight, 0, 0, 0);
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -self.kHeight, self.tableView.frame.size.width, self.kHeight)];
    self.imageView.clipsToBounds = YES;
    self.imageView.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longDidPress:)];
    longPress.allowableMovement = 100;
    [self.imageView addGestureRecognizer:longPress];
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:zoomModle.icon[@"url"]]];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.tableView addSubview:self.imageView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    if ([passWord isEqualToString:@"Night"]) {
        self.tableView.backgroundColor = [UIColor blackColor];
    }else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    [self.tableView reloadData];
}
//
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat yOffset  = scrollView.contentOffset.y;
    if (yOffset < -self.kHeight) {
        CGRect f = self.imageView.frame;
        f.origin.y = yOffset;
        f.size.height =  -yOffset;
        self.imageView.frame = f;
    }
}

- (instancetype)initWithURL:(NSString *)url
{
    self = [super init];
    if (self) {
        self.url = url;
    }
    return self;
}
#pragma mark - tableviewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_dataSource.count) {
        return _dataSource.count + 1;
    }
    return 0;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return CGFLOAT_MIN;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 50;
    }else {
        return 80;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    YXYZoomImageModel *zoomModle = [_dataSource lastObject];
    if (indexPath.row == 0) {
        YXYZoomIdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXYZoomIdTableViewCellIdentifier"];
        [cell setZoomImageModel:_dataSource[indexPath.row]];
        if ([passWord isEqualToString:@"Night"]) {
            cell.backgroundColor = [UIColor blackColor];
        }else {
            cell.backgroundColor = [UIColor whiteColor];
        }
        return cell;
    }else {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        for (int i = 0; i < zoomModle.relatedArray.count; i++) {
            YXYZoomRelatedModel *replyModel = zoomModle.relatedArray[i];
            [array addObject:replyModel.icon[@"url_l"]];
            [self.urlArray addObject:replyModel.next];
        }
        YXYScrollImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXYScrollImageTableViewCellIdentifier"];
        cell.correlation.text = @"相关信息";
        [cell.correlation nightMode];
        [cell setDataSource:array];
        [cell setUrlArray:self.urlArray];
        cell.delegate = self;
        if ([passWord isEqualToString:@"Night"]) {
            cell.backgroundColor = [UIColor blackColor];
        }else {
            cell.backgroundColor = [UIColor whiteColor];
        }
        return cell;
//    }else {
//        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
//        for (int i = 0; i < zoomModle.albumsArray.count; i++) {
//            YXYZoomAlbumsModel *zoomAlbumsModel = zoomModle.albumsArray[i];
//            [array addObject:zoomAlbumsModel.icon[@"url"]];
//        }
//        YXYZoomSelectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXYZoomSelectionTableViewCellIdentifier"];
//        [cell setDataSource:array];
//        cell.selection.text = @"精选集";
//        return cell;
    }
}

#pragma mark - 分享
- (void)shareDidPress:(UIBarButtonItem *)sender {
    YXYZoomImageModel *zoomModle = [_dataSource lastObject];
    NSArray *share = zoomModle.share[@"txts"];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5674be1867e58e561d001340"
                                      shareText:share[2][@"txt"]
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                       delegate:nil];
}

#pragma mark - delegate
- (void)scrollImageSkip:(NSString *)url {
    YXYSkipJumpViewController *skipJumpVC = [[YXYSkipJumpViewController alloc] initWithURL:url];
    [self.navigationController pushViewController:skipJumpVC animated:YES];
//    [skipJumpVC copy];
    [skipJumpVC release];
}

#pragma mark - 下载图片
- (void)longDidPress:(UILongPressGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.downloadImage = (UIImageView *)recognizer.view;
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"您确定要下载嘛?" preferredStyle:UIAlertControllerStyleAlert];
        [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        }]];
        [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImageWriteToSavedPhotosAlbum(self.downloadImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }]];
        [self presentViewController:alertView animated:YES completion:nil];
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error == nil) {
        [ProgressHUD showSuccess:@"保存成功"];
    }else{
        [ProgressHUD showSuccess:@"保存失败"];
    }
}

#pragma mark - back
- (void)backDidButton:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
